package com.shujia.weather.demo1;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

class MyMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        //开始处理我们数据
        //2007-02-27 03:07:13	37
        String[] strings = value.toString().split("\t");

        //将年月抽取出来，当作key
        context.write(new Text(strings[0].substring(0, 7)), new LongWritable(Long.parseLong(strings[1])));
    }
}

class MyReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
    @Override
    protected void reduce(Text key, Iterable<LongWritable> values, Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        //声明一个变量统计最高气温
        long max = 0L;
        for (LongWritable value : values) {
            //判断是否大于max
            if (value.get() > max) {
                max = value.get();
            }
        }
        context.write(key, new LongWritable(max));
    }
}


public class WeatherDemo {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        //获取hadoop的配置
        Configuration conf = new Configuration();
        //实例化job
        Job job = Job.getInstance(conf);
        job.setJobName("统计每年每月最高气温");
        job.setNumReduceTasks(2);
        job.setJarByClass(WeatherDemo.class);
        job.setCombinerClass(MyReducer.class);

        //设置map和reduce的类
        job.setMapperClass(MyMapper.class);
        job.setReducerClass(MyReducer.class);
        //设置map输出的key和value的类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        //设置reduce输出的key和value的类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        //设置数据的输入路径和结果输出路径
        FileInputFormat.setInputPaths(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));


        //提交任务，开始运行
        job.waitForCompletion(true);


    }
}
